﻿//Copyright 2010 http://tv4home.codeplex.com
//This file is part of TV4Home.Client.QuickEPG.
//TV4Home.Client.QuickEPG is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version.
//TV4Home.Client.QuickEPG is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//You should have received a copy of the GNU Lesser General Public License along with TV4Home.Client.QuickEPG. If not, see http://www.gnu.org/licenses/.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ServiceModel;
using TV4Home.Server.TVEInteractionLibrary.Interfaces;

namespace TV4Home.Client.Desktop.QuickEPG
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        ITVEInteraction tvWebClient;
     
        private const int WM_SYSCOMMAND = 0x112;
        private readonly static TimeSpan DOUBLE_CLICK_SPAN = TimeSpan.FromMilliseconds(500);

        Pages.MainPage channels = new Pages.MainPage();
        Pages.Schedules schedules = new Pages.Schedules();

        private DateTime _headerLastClick = DateTime.MinValue;

        public MainWindow()
        {
            InitializeComponent();
            //grdRoot.Children.Add(quickepg);
            LoadPage();
        }
        public void LoadPage()
        {
            if (!String.IsNullOrEmpty(Properties.Settings.Default.ServerName))
            {
                MainFrame.Navigate(channels);
            }
            else
            {
                ChangeVisibility(System.Windows.Visibility.Visible);
            }
        }
        private void btnSettings_Click(object sender, RoutedEventArgs e)
        {
            chbIsIntranet.IsChecked = Properties.Settings.Default.IsIntranet;

            tbServerName.Text = Properties.Settings.Default.ServerName;
            if (Properties.Settings.Default.ServerName != "")
            {
                GetTVServerData((bool)chbIsIntranet.IsChecked, tbServerName.Text);

            }
            else
            {
                ChangeVisibility(System.Windows.Visibility.Visible);
            }
        }

        private void ChangeVisibility(Visibility visible)
        {
            switch (visible)
            {
                case System.Windows.Visibility.Hidden:
                    brdSettings.Visibility = System.Windows.Visibility.Hidden;
                    lblGroups.Visibility = System.Windows.Visibility.Hidden;
                    lblServerName.Visibility = System.Windows.Visibility.Hidden;
                    cbChooseGroup.Visibility = System.Windows.Visibility.Hidden;
                    chbIsIntranet.Visibility = System.Windows.Visibility.Hidden;
                    btnCheckServer.Visibility = System.Windows.Visibility.Hidden;
                    btnSave.Visibility = System.Windows.Visibility.Hidden;
                    tbServerName.Visibility = System.Windows.Visibility.Hidden;
                    complete_overlay.Visibility = System.Windows.Visibility.Hidden;
                    details_overlay.Visibility = System.Windows.Visibility.Hidden;
                    btnCloseSettings.Visibility = System.Windows.Visibility.Hidden;
                    topRectangle.Visibility = System.Windows.Visibility.Hidden;
                    break;
                case System.Windows.Visibility.Visible:
                    brdSettings.Visibility = System.Windows.Visibility.Visible;
                    lblGroups.Visibility = System.Windows.Visibility.Visible;
                    lblServerName.Visibility = System.Windows.Visibility.Visible;
                    cbChooseGroup.Visibility = System.Windows.Visibility.Visible;
                    chbIsIntranet.Visibility = System.Windows.Visibility.Visible;
                    btnCheckServer.Visibility = System.Windows.Visibility.Visible;
                    btnSave.Visibility = System.Windows.Visibility.Visible;
                    tbServerName.Visibility = System.Windows.Visibility.Visible;
                    complete_overlay.Visibility = System.Windows.Visibility.Visible;
                    details_overlay.Visibility = System.Windows.Visibility.Visible;
                    btnCloseSettings.Visibility = System.Windows.Visibility.Visible;
                    topRectangle.Visibility = System.Windows.Visibility.Visible;
                    break;

            }

        }

        private void complete_overlay_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ChangeVisibility(System.Windows.Visibility.Hidden);
        }
        private void GetTVServerData(bool isIntranet, string serverName)
        {
            try
            {
                if (tvWebClient == null)
                {
                    tvWebClient = Connect(serverName, isIntranet);
                }
                if (tvWebClient != null)
                {
                    List<WebChannelGroup> groups = tvWebClient.GetGroups();
                    cbChooseGroup.ItemsSource = groups;
                    cbChooseGroup.InvalidateVisual();
                    if (Properties.Settings.Default.DefaultGroup != 1)
                    {
                        for (int i = 0; i < groups.Count; i++)
                        {
                            if (Properties.Settings.Default.DefaultGroup == groups[i].IdGroup)
                            {
                                cbChooseGroup.SelectedIndex = i;
                                break;
                            }
                        }
                    }
                    else
                    {
                        cbChooseGroup.SelectedIndex = 0;
                    }
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show("Error in GetTVServerData" + ex.ToString());
            }
        }
        public void ConnectToService()
        {
            try
            {
                tvWebClient = Connect(Properties.Settings.Default.ServerName, Properties.Settings.Default.IsIntranet);
            }
            catch (Exception ex)
            {
                //if connection is not possible ask whether it retry or not
                string sMessageBoxText = "Verbindung konnte nicht hergestellt werden. Erneut versuchen?";
                string sCaption = "QuickEPG";

                MessageBoxButton btnMessageBox = MessageBoxButton.YesNo;
                MessageBoxImage icnMessageBox = MessageBoxImage.Warning;

                MessageBoxResult rsltMessageBox = MessageBox.Show(sMessageBoxText, sCaption, btnMessageBox, icnMessageBox);


                // Process message box results

                switch (rsltMessageBox)
                {

                    case MessageBoxResult.Yes:
                        ConnectToService();

                        break;
                    case MessageBoxResult.No:

                        break;
                }
            }

        }
        private ITVEInteraction Connect(string serverName, bool isIntranet)
        {
            if (!String.IsNullOrEmpty(serverName))
            {
                switch (isIntranet)
                {
                    case true:
                        return ChannelFactory<ITVEInteraction>.CreateChannel(new BasicHttpBinding() { MaxReceivedMessageSize = 10000000 }, new EndpointAddress(String.Format(Properties.Settings.Default.IntranetUrl, serverName)));
                    case false:
                        return ChannelFactory<ITVEInteraction>.CreateChannel(new BasicHttpBinding() { MaxReceivedMessageSize = 10000000 }, new EndpointAddress(String.Format(Properties.Settings.Default.InternetUrl, serverName)));
                }
            }

            return null;
        }
        private void btnCheckServer_Click(object sender, RoutedEventArgs e)
        {
            if (tbServerName.Text != "")
            {
                try
                {
                    GetTVServerData((bool)chbIsIntranet.IsChecked, tbServerName.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error in ButtonCheckServer" + ex.ToString());
                }
            }
        }
        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void RestoreButton_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = (this.WindowState == WindowState.Normal) ? WindowState.Maximized : WindowState.Normal;
        }

        private void MinimizeButton_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }
        private void btnCloseSettings_Click(object sender, RoutedEventArgs e)
        {
            complete_overlay_MouseLeftButtonDown(this, null);
        }
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            Properties.Settings.Default.IsIntranet = (bool)chbIsIntranet.IsChecked;
            bool hasChanged = false;
            if (Properties.Settings.Default.ServerName != tbServerName.Text && !String.IsNullOrEmpty(tbServerName.Text))
            {
                hasChanged = true;
            }

            if (!String.IsNullOrEmpty(tbServerName.Text))
            {

                Properties.Settings.Default.ServerName = tbServerName.Text;
                if (cbChooseGroup.SelectedItem is WebChannelGroup)
                {
                    Properties.Settings.Default.DefaultGroup = ((WebChannelGroup)cbChooseGroup.SelectedItem).IdGroup;
                }
                else
                {
                    Properties.Settings.Default.DefaultGroup = 1;
                }
                Properties.Settings.Default.Save();
                ChangeVisibility(System.Windows.Visibility.Hidden);
                if (hasChanged)
                {
                    if (!MainFrame.CanGoBack)
                    {
                        MainFrame.Navigate(channels);
                    }
                    channels.FetchChannelData();
                }
            }

        }
        private void Header_Drag(object sender, MouseButtonEventArgs e)
        {
            if (DateTime.Now.Subtract(_headerLastClick) <= DOUBLE_CLICK_SPAN)
            {
                this.WindowState = (this.WindowState == WindowState.Normal) ? WindowState.Maximized : WindowState.Normal;
            }
            _headerLastClick = DateTime.Now;

            if (Mouse.LeftButton == MouseButtonState.Pressed) this.DragMove();
        }

        private void btnBack_Click(object sender, RoutedEventArgs e)
        {
            MainFrame.Navigate(schedules);
        }

   
    }
}
